package com.lkx.farmershop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lkx.farmershop.common.api.ApiResult;
import com.lkx.farmershop.mapper.CollectMapper;
import com.lkx.farmershop.model.entity.*;
import com.lkx.farmershop.model.vo.CollectVo;
import com.lkx.farmershop.model.vo.SimpleUserVo;
import com.lkx.farmershop.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (Collect)表服务实现类
 *
 * @author makejava
 * @since 2025-02-09 15:34:57
 */
@Service("collectService")
public class CollectServiceImpl extends ServiceImpl<CollectMapper, Collect> implements CollectService {

    @Autowired
    private TuanService tuanService;
    @Autowired
    private IFarmerService farmerService;
    @Autowired
    private TagService tagService;
    @Autowired
    private TagTuanService tagTuanService;
    @Autowired
    private UserWordService userWordService;

    @Override
    public ApiResult<String> collectGroup(Long tuanId, Long userId) {


        Collect collect = lambdaQuery().eq(Collect::getUserId, userId)
                .eq(Collect::getTuanId, tuanId).one();
        if(collect==null){
            //若没有收藏过，则添加收藏
            save(new Collect(tuanId, userId));

            //添加用户关键词
            addUserWord(tuanId, userId, tagTuanService, tagService, userWordService);

            return ApiResult.success("已添加收藏");
        }else{
            //若已收藏过，则取消收藏，删除收藏信息
            removeById(collect);
            return ApiResult.success("已取消收藏");
        }
    }

    static void addUserWord(Long tuanId, Long userId, TagTuanService tagTuanService, TagService tagService, UserWordService userWordService) {
        List<TagTuan> tagTuanList = tagTuanService.lambdaQuery().eq(TagTuan::getTuanId, tuanId).list();
        if (tagTuanList != null && !tagTuanList.isEmpty()){
            List<Long> ids = tagTuanList.stream().map(TagTuan::getTagId).collect(Collectors.toList());
            List<String> names = tagService.lambdaQuery().in(Tag::getId, ids).list()
                    .stream().map(Tag::getTagname).collect(Collectors.toList());
            for (String name : names) {
                UserWord one = userWordService.getOne(new LambdaQueryWrapper<UserWord>()
                        .eq(UserWord::getUserId, userId)
                        .eq(UserWord::getWord, name));
                if ( one == null) {
                    UserWord userWord = new UserWord(userId, name, 1);
                    userWordService.save(userWord);
                }else {
                    userWordService.update(new LambdaUpdateWrapper<UserWord>()
                            .eq(UserWord::getUserId, userId)
                            .eq(UserWord::getWord, name)
                            .setSql("count = count + 1"));
                }
            }
        }
    }

    @Override
    public ApiResult<Boolean> hasCollected(Long tuanId, Long userId) {
        Collect collect = lambdaQuery().eq(Collect::getUserId, userId)
                .eq(Collect::getTuanId, tuanId).one();
        return ApiResult.success(collect!=null);
    }

    @Override
    public ApiResult<List<CollectVo>> getCollectList(Long userId) {
        List<Collect> collectList = lambdaQuery().eq(Collect::getUserId, userId).list();
        if(collectList==null || collectList.isEmpty()){
            return ApiResult.success(new ArrayList<>());
        }
        List<CollectVo> collectVoList = collectList.stream().map(collect -> {
            CollectVo collectVo = new CollectVo();
            //设置组团信息
            collectVo.setTuanId(collect.getTuanId());
            Tuan tuan = tuanService.getById(collect.getTuanId());
            collectVo.setTuanTitle(tuan.getTuanTitle());
            collectVo.setTuanDetail(tuan.getTuanDetail());
            //设置简化的用户信息
            SimpleUserVo simpleUserVo = new SimpleUserVo();
            Farmer user = farmerService.getById(collect.getUserId());
            simpleUserVo.setUserId(user.getFarmerId());
            simpleUserVo.setUserName(user.getName());
            simpleUserVo.setAvatar(user.getAvatar());
            collectVo.setSimpleUserVo(simpleUserVo);

            return collectVo;
        }).collect(Collectors.toList());

        // 翻转collect顺序
        java.util.Collections.reverse(collectVoList);
        return ApiResult.success(collectVoList);
    }
}

